<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        th {
            position: sticky;
            top: 0;
            z-index: 1;
            background-color: #f2f2f2;
        }

        .footer {
            width: 100%;
            height: 50px;
            background: linear-gradient(to right, #f0ecf4, #b5c2d7);
            display: flex;
            align-items: center;
            justify-content: center;
            position: fixed;
            bottom: 0;
            z-index: 2;
        }

        body {
            padding-bottom: 70px;
            /* 确保内容不会被底部栏遮挡 */
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination button,
        .pagination input {
            margin: 0 5px;
            padding: 5px 10px;
            cursor: pointer;
            border: 1px solid #dcdfe6;
            background-color: #fff;
            color: #606266;
            outline: none;
        }

        .pagination button:hover {
            color: #409eff;
        }

        .pagination button.active {
            background-color: #409eff;
            color: #fff;
        }

        .pagination input {
            width: 50px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div
        style="display: flex;flex-direction: row;justify-content: space-evenly;align-items: center;background:linear-gradient(to right, #f0ecf4, #b5c2d7)">
        <h1
            style="font-size: 20px;font-weight: normal;border: 1px solid blue;background-color: rgb(130, 130, 234);padding: 15px;">
            信息回传界面</h1>
        <!-- <a href="./tiaoshi" style="text-decoration: none;color: black;">调试工具</a>
    <a href="./config" style="text-decoration: none;color: black;">一分二滚筒</a>
    <a href="./configFour" style="text-decoration: none;color: black;">一分四滚筒</a> -->
    </div>
    <table id="data-table">
        <thead>
            <tr>
                <th>序号</th>
                <th>运单号</th>
                <th>重量（kg）</th>
                <th>长度（mm）</th>
                <th>宽度（mm）</th>
                <th>高度（mm）</th>
                <th>体积（m³）</th>
                <th>扫描时间</th>
                <th>状态</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <div class="pagination" id="pagination">
        <!-- 页码按钮将在这里动态生成 -->
    </div>
    <div class="search-container" style="text-align: center; margin-top: 30px;">
        <input type="text" id="search-input" placeholder="输入运单号"
            style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; outline: none;">
        <button id="search-button"
            style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">查询</button>
    </div>
    <!-- 旺店通版本选择区域 -->
    <div style="display: flex;flex-direction: column;">
        <form id="myForm" action="" onsubmit="return collectValues(event)">
            <label for="email">旺店通版本选择:</label>
            <!-- <input list="email-list" id="email" name="email" required>
      <datalist id="email-list"></datalist><br><br> -->
            <select id="email" name="email" required>
                <option id="emailDefault" value=""></option>
                <option id="emailDefault" value="1">旺店通企业版</option>
                <option id="emailDefault" value="2">旺店通旗舰版</option>
                <option id="emailDefault" value="3">旺店通慧经营</option>
            </select><br><br>
            <button id="submitVersion"
                style="width: 60px;height: 30px;border-radius: 10px;background-color: #272f36;color: white;"
                onclick="collectValues">保存</button>
        </form>
    </div>
    <!-- <div>
    <button id="switchMode-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #573333; color: #e7ebf3; cursor: pointer; outline: none;">切换上传</button>
    <h3 style="display: inline-block;">当前为：<h3 style="display: inline-block;" id="switchMode">Loading...</h3></h3>
  </div> -->
    <!-- <button id="switch-button"
    style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #a3130c; color: white; cursor: pointer; outline: none;">点击切换流水线状态</button> -->
    <div class="results-container" id="results-container">
        <!-- 查询结果将显示在这里 -->
    </div>
    <script>
        let ws;
        let currentPage = 1;
        let totalPages = 1;
        const limit = 10; // 每页显示的记录数
        let showData = false
        function startWebSocket() {
            ws = new WebSocket('ws://127.0.0.1:3000');

            ws.onopen = () => {
                console.log('WebSocket connection established');
            };

            ws.onmessage = (event) => {
                if (event.data === 'ping') {
                    ws.send(JSON.stringify({ info: 'pong' }));
                    return;
                }
                if (event.data === 'logMessage') {
                    fetchLogs(currentPage)
                }
            };

            ws.onclose = () => {
                console.log('WebSocket connection closed');
                setTimeout(startWebSocket, 2000);
            };

            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
                setTimeout(startWebSocket, 2000);
            };
        }

        function fetchLogs(page) {
            fetch(`http://localhost:3001/logs?page=${page}&limit=${limit}`)
                .then(response => response.json())
                .then(data => {
                    showData = data.results.some(log => log.mapData.volume !== undefined && log.mapData.volume !== null && log.mapData.volume !== ''); // 检查是否有记录包含体积数据
                    renderTable(data.results);
                    totalPages = Math.ceil(data.total / limit);
                    createPagination();
                })
                .catch(error => console.error('Error fetching logs:', error));
        }

        function renderTable(logs) {
            const tableBody = document.querySelector('#data-table tbody');
            tableBody.innerHTML = '';

            const tableHead = document.querySelector('#data-table thead tr');
            if (showData) {
                tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>长度（mm）</th>
      <th>宽度（mm）</th>
      <th>高度（mm）</th>
      <th>体积（m³）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
            } else {
                tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
            }

            logs.forEach((log, index) => {
                const row = document.createElement('tr');
                if (showData) {
                    row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${log.mapData.code}</td>
        <td>${log.mapData.weight}</td>
        <td>${log.mapData.length}</td>
        <td>${log.mapData.width}</td>
        <td>${log.mapData.height}</td>
        <td>${log.mapData.volume}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
                } else {
                    row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${log.mapData.code}</td>
        <td>${log.mapData.weight}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
                }

                tableBody.appendChild(row);
            });
        }

        function createPagination() {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            const maxVisiblePages = 3; // 最多显示的页码数
            const halfMaxVisiblePages = Math.floor(maxVisiblePages / 2);

            let startPage = Math.max(1, currentPage - halfMaxVisiblePages);
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            startPage = Math.max(1, endPage - maxVisiblePages + 1);

            for (let i = startPage; i <= endPage; i++) {
                const button = document.createElement('button');
                button.textContent = i;
                button.classList.add('page-button');
                if (i === currentPage) {
                    button.classList.add('active');
                }
                button.addEventListener('click', () => {
                    currentPage = i;
                    fetchLogs(currentPage);
                });
                pagination.appendChild(button);
            }

            if (startPage > 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                pagination.insertBefore(ellipsis, pagination.firstChild);
            }

            if (endPage < totalPages) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                pagination.appendChild(ellipsis);
            }

            const gotoInput = document.createElement('input');
            gotoInput.type = 'number';
            gotoInput.min = 1;
            gotoInput.max = totalPages;
            gotoInput.placeholder = 'Go to';
            gotoInput.addEventListener('keydown', (event) => {
                if (event.key === 'Enter') {
                    const gotoPage = parseInt(gotoInput.value, 10);
                    if (!isNaN(gotoPage) && gotoPage >= 1 && gotoPage <= totalPages) {
                        currentPage = gotoPage;
                        fetchLogs(currentPage);
                    }
                }
            });
            pagination.appendChild(gotoInput);
        }

        function displayResults(logs) {
            const resultsContainer = document.getElementById('results-container');
            resultsContainer.innerHTML = ''; // 清空之前的查询结果

            if (logs.length === 0) {
                resultsContainer.innerHTML = '<h2>没有找到匹配的日志</h2>';
                return;
            }

            const ul = document.createElement('ul');
            logs.forEach(log => {
                const li = document.createElement('li');
                li.innerHTML = `
                    <strong>运单号:</strong> ${log.mapData.code}<br>
                    <strong>响应:</strong> ${log.response}<br>
                    <strong>时间:</strong> ${log.formattedTime}
                `;
                ul.appendChild(li);
            });

            resultsContainer.appendChild(ul);
        }

        // 更改旺店通版本接口请求
        function getVersion(name, value) {
            let url
            if (name === 'select') {
                url = `http://localhost:3001/wdt/switchVersion?name=${name}`
            } else {
                url = `http://localhost:3001/wdt/switchVersion?name=${name}&value=${value}`
            }
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 更改成功   根据返回的版本号来渲染dom
                            if (data.data.value == 1) {
                            // 企业版
                            document.getElementById('emailDefault').innerText = '旺店通企业版';
                           if(name==='switch'){
                            alert('修改成功,当前为旺店通企业版')
                           }

                        } else if (data.data.value == 2) {
                            // 旗舰版 
                            document.getElementById('emailDefault').innerText = '旺店通旗舰版';
                            if(name==='switch'){
                            alert('修改成功,当前为旺店通旗舰版')
                            }
                        } else {
                            // 慧经营
                            if(name==='switch'){
                            document.getElementById('emailDefault').innerText = '旺店通慧经营';
                            alert('修改成功,当前为旺店通慧经营版')
                            }
                        }

                    } else {
                        // 数据库更改失败
                        alert('更改版本失败，请检查原因')
                    }
                    //   showData = data.results.some(log => log.mapData.volume !== undefined && log.mapData.volume !== null && log.mapData.volume !== ''); // 检查是否有记录包含体积数据
                    //   renderTable(data.results);
                    //   totalPages = Math.ceil(data.total / limit);
                    //   createPagination();
                })
                .catch(error => console.error('Error fetching logs:', error));
        }

        startWebSocket();
        fetchLogs(currentPage); // 初始加载第一页数据
        getVersion('select')  //   初始获取版本
        document.getElementById('search-button').addEventListener('click', () => {
            const searchCode = document.getElementById('search-input').value.trim();
            if (searchCode) {
                fetch(`http://localhost:3001/logs/selectLog?code=${searchCode}`)
                    .then(response => response.json())
                    .then(data => {
                        displayResults(data.logs);
                    })
                    .catch(error => console.error('Error fetching logs:', error));
            } else {
                alert('请输入运单号');
            }
        });

        function collectValues(event) {
            event.preventDefault();
            const data = document.getElementById('email').value
            if (data == 1) {
                getVersion('switch', 1)
            } else if (data == 2) {
                getVersion('switch', 2)
            } else {
                getVersion('switch', 3)
            }
            // document.getElementById('email').addEventListener('onClick', async function (event) {
            // event.preventDefault(); // 阻止表单默认提交行为
            // const formData = new FormData(this);
            // const data = {};
            // formData.forEach((value, key) => {
            //     data[key] = value;
            // });
            // console.log(data, 'form表单数据');

            //   const response = await fetch(`http://localhost:3001/updateYunDaInfo?next=${data.name}&empCode=${data.email.slice(0, 4)}`, {
            //     method: 'GET',
            //     headers: {
            //       'Content-Type': 'application/json'
            //     }
            //   });
            //   if (response.status === 200) {
            //     alert('修改成功')
            //   } else {
            //     alert('修改失败')
            //   }

            // });
        }

        // document.getElementById('switch-button').addEventListener('click', () => {
        //     fetch(`http://localhost:3001/switch`)
        //       .then(response => response.json())
        //       .then(data => {
        //           alert('切换成功')
        //       })
        //       .catch(error => console.error('Error fetching logs:', error));
        // });


        // document.getElementById('switchMode-button').addEventListener('click', () => {
        //   fetch('http://localhost:3001/switchMode?mode=1')
        //     .then(response => {
        //       if (!response.ok) {
        //         throw new Error('Network response was not ok ' + response.statusText);
        //       }
        //       return response.json(); // 解析JSON数据
        //     })
        //     .then(data => {
        //         document.getElementById('switchMode').innerText = data;
        //     })
        //     .catch(error => {
        //       console.error('Error fetching switch mode:', error);
        //     });
        // });
        // document.addEventListener('DOMContentLoaded', function () {
        //   fetch('http://localhost:3001/switchMode')
        //     .then(response => response.text())
        //     .then(data => {
        //       document.getElementById('switchMode').innerText = data;
        //     })
        //     .catch(error => {
        //       console.error('Error fetching switch mode:', error);
        //     });
        // });


    </script>
    <div class="footer">
        <div class="foo_main">杭州黎行科技有限公司&copy; 版权所有 </div>
    </div>
</body>

</html>